import React, { useEffect, useRef, useState } from "react";
import { Button, Form, Input, Space, DatePicker, Select, Upload } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import { getDateTime3 } from '@/utils/getDate'
import { UploadOutlined } from "@ant-design/icons";
import _ from 'lodash'
import { apiPlatformActivitySheetPage, apiPlatformActivitySheetExcelExport, apiPlatformActivitySheetUpdateActivityStatus, apiGetActivityConfig, apiPlatformActivitySheetDel } from '@/request/activityManager'
import { apiTSysDictionariesView, apiTSysDictionariesEdit } from '@/request/storageManager/store.js'
import upload from "../app/Evaluate/component/upload";
import axios from 'axios'
import TheUpload from "@/components/TheUpload";
const { RangePicker } = DatePicker;

const SearchHeader = ({ goAdd, setValue, onUpload, onPriceUpload }) => {
    const formRef = useRef()
    const [optionType, setOptionType] = useState([])
    const [levelsStatus, setLevelsStatus] = useState([
        { label: 'S', value: 'S' },
        { label: 'A', value: 'A' },
        { label: 'B', value: 'B' },
        { label: 'C', value: 'C' }
    ])
    const [optionStatus, setOptionStatus] = useState([
        { label: '正常', value: '0' },
        { label: '关闭', value: '1' }
    ])
    const onFinish = values => {
        _.forIn(values, (v, k) => {
            if (!v) {
                delete (values[k])
            }
        })
        setValue(values)
    }
    const reset = () => {
        formRef.current.setFieldsValue({
            activityType: null,
            activityName: '',
            activityStatus: null,
            activityLevel: null
        })
        setValue({})
    }
    useEffect(async () => {
        const res = await apiGetActivityConfig({ platformSetKey: 'ACTIVITY_TYPE' })
        if (res.code === 0) {
            setOptionType(res.data.map(item => {
                return {
                    label: item.platformSetShowValue,
                    value: item.platformSetUseValue
                }
            })
            )
        }

    }, [])
    return (
        <div
            className="p-search-box"
            style={{ display: "flex", justifyContent: "space-between" }}
        >
            <Form ref={formRef} layout="inline" onFinish={onFinish}>
                <Form.Item name={"activityName"}>
                    <Input
                        style={{ width: 160 }}
                        suffix={<SearchOutlined />}
                        placeholder={"活动名称"}
                    />
                </Form.Item>
                {/* <Form.Item name={"time"} >
                    <RangePicker />
                </Form.Item> */}
                <Form.Item name={"activityType"}>
                    <Select style={{ width: 140 }} options={optionType} placeholder={"请选择活动类型"} allowClear />
                </Form.Item>
                <Form.Item name={"activityStatus"}>
                    <Select style={{ width: 140 }} options={optionStatus} placeholder={"请选择活动状态"} allowClear />
                </Form.Item>
                <Form.Item name={"activityLevel"}>
                    <Select style={{ width: 140 }} options={levelsStatus} placeholder={"请选择活动等级"} allowClear />
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button htmlType="submit" type="primary">搜索</Button>
                        <Button onClick={reset}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
            <Space>
                {/* <TheButton haspermi={['activityManager:upload']} type="default" size="middle" onClick={onUpload}>
                    上传活动
                </TheButton> */}
                <TheButton haspermi={['activityManager:price:upload']} type="primary" size="middle" onClick={onPriceUpload}>
                    配置价格图片
                </TheButton>
                <TheButton haspermi={['activityManager:add']} type="default" size="middle" onClick={goAdd}>
                    创建活动
                </TheButton>
            </Space>
        </div>
    );
};

class ActivityList extends React.Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            optionType: [],
            optionWay: [],
            columns: [
                {
                    title: "活动名称",
                    dataIndex: "activityName",
                    key: "activityName",
                },
                {
                    title: "门店名称",
                    dataIndex: "storeName",
                    key: "storeName",
                },
                // {
                //     title: "结束时间",
                //     dataIndex: "petName",
                //     key: "petName",

                // },
                {
                    title: "活动类型",
                    key: "activityType", render: (text, render) => {
                        let obj = this.state.optionType.find(item => item.value === text.activityType)
                        return obj && obj.label;
                    },

                },
                {
                    title: "活动链接/活动ID",
                    dataIndex: "activityId",
                    key: "activityId",
                },
                {
                    title: "活动状态",
                    key: "activityStatus", render: (text, render) => {
                        let txt = ''
                        switch (text.activityStatus) {
                            case 0:
                                txt = '正常'
                                break;
                            case 1:
                                txt = '关闭'
                                break;
                            default:
                                break;
                        }
                        return txt;
                    },
                },
                {
                    title: "定时任务",
                    key: "activityTime", render: (text, render) => {
                        let txt = ''
                        switch (text.timeType) {
                            case '0':
                                txt = '/'
                                break;
                            case '1':
                                txt = text.startTime + '至' + text.endTime
                                break;
                            default:
                                txt = '/'
                                break;
                        }
                        return txt;
                    },
                },
                {
                    title: "活动方式",
                    key: "activityWay",
                    render: (text, render) => {
                        let obj = this.state.optionWay.find(item => item.value == text.activityWay)
                        return obj && obj.label || '/';
                    },
                },
                {
                    title: "活动等级",
                    key: "activityLevel",
                    render: (text, render) => {

                        return text.activityLevel;
                    },
                },
                {
                    title: "操作",
                    width: 250,
                    fixed: 'right',
                    render: (text, render) => {
                        return (
                            <div>
                                <TheButton haspermi={['activityManager:edit']} onClick={() => this.props.history.push('/activityManager/edit/' + text.activityId)} >编辑</TheButton>
                                <TheButton haspermi={['activityManager:joinUser']} onClick={() => this.props.history.push('/activityManager/joinUser/' + text.activityId)} >参与用户</TheButton>
                                {
                                    ['NEW_COME', 'SHOP_GOODS'].includes(text.activityType) ?
                                        <TheButton haspermi={['activityManager:exportActivity']} onClick={() => this.exportActivity(text)} >导出活动</TheButton>
                                        : null
                                }

                                {
                                    (text.activityStatus === 0 ? <TheButton haspermi={['activityManager:update']} onClick={() => this.updateActivity(text.activityId, '1')}>结束活动</TheButton> : <TheButton haspermi={['activityManager:update']} onClick={() => this.updateActivity(text.activityId, '0')}>开启活动</TheButton>)
                                }
                                <TheButton haspermi={['activityManager:delete']} onClick={() => this.deleteActivity(text.activityId)} >删除</TheButton>
                            </div>
                        );
                    },
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            total: 0,
            searchValue: {},
            visible: false,
            title: '',
            loading: false,
            priceVisible: false,
            configPrice: [],
            initialValues:{
                value:''
            }
        }
    }
    async componentDidMount() {
        this.getConfigTypes('ACTIVITY_TYPE')
        this.getConfigTypes('ACTIVITY_WAY')
        this.getData()
    }
    async exportActivity(row) {
        const res = await apiPlatformActivitySheetExcelExport({ activityId: row.activityId })
        let a = document.createElement("a");
        let url = window.URL.createObjectURL(new Blob([res]));
        console.log(url, 'url');
        a.href = url;
        a.download = row.activityName + '(' + row.activityId + ')' + ".xlsx";
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
    }
    async getConfigTypes(platformSetKey) {
        const res = await apiGetActivityConfig({ platformSetKey })
        if (res.code === 0) {
            if (platformSetKey === 'ACTIVITY_TYPE') {
                this.setState({
                    optionType: res.data.map(item => {
                        return {
                            label: item.platformSetShowValue,
                            value: item.platformSetUseValue
                        }
                    })
                })
            } else {
                this.setState({
                    optionWay: res.data.map(item => {
                        return {
                            label: item.platformSetShowValue,
                            value: item.platformSetUseValue
                        }
                    })
                })
            }

        }
    }
    async deleteActivity(activityId) {
        let res = await apiPlatformActivitySheetDel({ activityId })
        if (res.code === 0) {
            React.$message({
                type: 'success',
                content: '操作成功'
            })
            this.setState({
                pageData: {
                    pageNo: 1,
                    pageSize: 10
                }
            }, () => {
                this.getData()

            })
            return false
        } else {
            React.$message({
                type: 'warning',
                content: res.codeMessage
            })
            return false
        }
    }
    async updateActivity(activityId, type) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定变更活动状态？",
            onOk: async () => {
                let res = await apiPlatformActivitySheetUpdateActivityStatus({ activityId, type })
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: '操作成功'
                    })
                    this.getData()
                    return false

                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                    return false
                }
            }
        });

    }
    onFinish() { }
    async getData() {
        let res = await apiPlatformActivitySheetPage({
            ...this.state.pageData, ...this.state.searchValue,
        })
        if (res.code === 0 && res.data) {
            this.setState({
                dataSource: res.data,
                total: res.totalCount
            })
        } else {
            React.$message({
                type: 'warning',
                content: res.codeMessage
            })
            return false
        }
    }
    goAdd = () => {
        this.props.history.push('/activityManager/add')
    }
    onUpload = () => {
        this.setState({
            visible: true,
            title: '上传活动',
            type: 'upload'
        })
    }

    onPriceUpload = async () => {
        const request = await apiTSysDictionariesView({ dictionariesId: '1646409212069236739' })
        if (request.code === 0) {
            let url = ''
            if (request.data.value !== '') {
                url = request.data.value
                this.setState({
                    configPrice: [
                        {
                            uid: new Date().getTime(),
                            name: 'image',
                            status: 'done',
                            url
                        }
                    ],
                })
            }
            this.setState({
                priceVisible: true,
                title: '配置价格图片',
                initialValues:{
                    value:url
                }
            })
        }
    }
    handleCancel = () => {
        this.setState({
            priceVisible: false,
            visible: false,
            title: '',
            type: '',
        })
    };
    onUploadFinish = () => {
        let { fileList } = this.state;
        let formData = new FormData();
        fileList.forEach((file) => {
            formData.append('file', file);
        });
        console.log(formData);
        // fetch(config.proxy.BASE_URL+'/goodsEvaluation/brushPraise', {
        //     method: "post",
        //     headers: {
        //         RSnetToken: sessionStorage.getItem('RSnetToken')
        //     },
        //     body: formData,
        // })
        //     .then((res) => {
        //         res.json().then(res => {
        //             if (res.code === 0) {
        //                 this.setState({fileList: []})
        //                 message.success('添加成功')
        //                 this.props.history.go(-1);
        //             } else {
        //                 message.error(res.codeMessage)
        //             }
        //         })
        //     })
        //     .catch((res) => {
        //         console.log(res);
        //         message.error('上传失败.');
        //     })
        //     .finally(() => {
        //         this.setState({loading:false});
        //         // setUploading(false);
        //     });

    }
    setValue = values => {
        this.setState({
            searchValue: values,
            pageData: {
                pageNo: 1,
                pageSize: 10
            }
        }, () => this.getData())
        console.log(values);
    }
    pageChange = (pageNo, pageSize) => {
        console.log(pageNo, pageSize);
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => this.getData())
    }
    getFileResult = (data) => {
        if (data.length > 0 && data[0].hasOwnProperty('response') && data[0].response) {
            let str = data[0].response.data
            this.formRef.setFieldsValue({ value: str })
        } else {
            this.formRef.setFieldsValue({ value: '' })
        }
    }
    priceFinish = async () => {
        let values = this.formRef.getFieldsValue()
        console.log(values);
        if(values.value === undefined ){
            values.value = ''
        }
        let res = await apiTSysDictionariesEdit({  dictionariesId: '1646409212069236739' , ...values })
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: res.codeMessage
            })
            this.handleCancel()
        }
    }
    render() {
        const { columns, fileList, dataSource, pageData, total, visible, title, loading, priceVisible, configPrice, initialValues } = this.state
        let filedata = {
            accept: ".xls,.xlsx,application/vnd.ms-excel",
            maxCount: 1,
            onRemove: (file) => {
                const index = fileList.indexOf(file);
                const newFileList = fileList.slice();
                newFileList.splice(index, 1);
                this.setState({
                    fileList: newFileList
                })
            },
            beforeUpload: (file) => {
                this.setState({
                    fileList: [file]
                })
                return false;
            },
            fileList,
        };
        return (
            <div className="p-layout-box">
                <SearchHeader setValue={this.setValue} goAdd={this.goAdd} onUpload={this.onUpload} onPriceUpload={this.onPriceUpload} />
                <div className="p-layout-content-pagination">
                    <TheTable
                        scroll={{ x: "max-content", y: '63vh' }}
                        columns={columns}
                        dataSource={dataSource}
                        pageData={pageData}
                    />
                    <ThePagination pageNo={pageData.pageNo} pageSize={pageData.pageSize} total={total} pageChange={this.pageChange} />
                </div>
                <TheDialog
                    width={500}
                    title={[
                        <div>{title} <span style={{ color: '#999', fontSize: '12px' }}>此处配置用于在商品价格旁边展示，增加活动氛围</span></div>
                    ]}
                    visible={priceVisible}
                    footer={null}
                    handleCancel={() => this.handleCancel()}
                >
                    <Form ref={(ref) =>  this.formRef = ref } onFinish={() => this.priceFinish()} initialValues={initialValues}>
                        <Form.Item label="配置价格图片" name="value" 
                            extra={`建议上传尺寸为138*52，大小不超过10M的图片`} 
                        >
                            <TheUpload isConversion={false} maxSize={10} data={{ attachKey: '1' }} len={1} fileList={configPrice}
                                getFileResult={this.getFileResult} />
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </TheDialog>
                <TheDialog
                    width={400}
                    title={title}
                    visible={visible}
                    footer={null}
                // handleCancel={this.closeDialog}
                >
                    <Form onFinish={(values) => this.onUploadFinish(values)}>
                        <Form.Item label="上传活动" name="upload">
                            <Upload {...filedata}>
                                <Button icon={<UploadOutlined />}>选择文件</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </TheDialog>
            </div>
        )
    }
}
export default ActivityList 
